<?php
/**
 * Created by PhpStorm.
 * User: mojie126
 * Date: 2017/4/27
 * Time: 下午10:57
 */

namespace app\index\controller;

use app\common\rbac;
use Base32\Base32;
use think\Controller;
use think\Session;

class Base extends Controller
{
	public function _initialize()
	{
		if (empty(cache("config"))) {
			$info = db("system_config")->value("config");
			cache("config", $info, 86400 * 365 * 10);
		}
		if (empty(Session::get("uid"))) {
			if (preg_match("/signup/i", getFullURL())) {
				$return = "";
			} else {
				$return = getFullURL();
			}
			$this->error("还未登录，请先登录", "/index/login?r=$return");
		}

		//获取当前页面pid为0的菜单项地址，并在相应的菜单项修添加<li>标签属性class="am-active"
	}

	/**
	 * 使用in_array()对两个二维数组取差集
	 *  - 去除$arr1 中 存在和$arr2相同的部分之后的内容
	 *
	 * @param $arr1
	 * @param $arr2
	 *
	 * @return array
	 */
	public function getDiffArray($arr1, $arr2)
	{
		return array_values(array_filter($arr1, function ($v) use ($arr2) {
			return !in_array($v, $arr2);
		}));
	}

	public function jsonReturnLayUI($code = 0, $msg = "", $count = 0, $data = [])
	{
		$result["code"] = $code;
		$result["msg"] = $msg;
		$result["count"] = $count;
		$result["data"] = $data;
		echo json_encode($result);
		exit;
	}

	public function key()
	{
		return trim(Base32::encode(random()), '=');
	}

	public function getAccess($path = "")
	{
		//给模板赋值，让模板判断是否有权限
		if (rbac::canAccess($path)) {
			$this->assign("access", "1");
		} else {
			$this->assign("access", "0");
		}
	}

	/**
	 * @param int $type 0=直接跳转，1=返回布尔值，2=返回JSON信息
	 *
	 * @return bool
	 */
	public function checkAccess($type = 0, $url = "", $path = "")
	{
		if ($type == 0) {
			if (!rbac::canAccess($path)) {
				$this->error("权限不足", $url);
			}
		} elseif ($type == 1) {
			if (!rbac::canAccess()) {
				return FALSE;
			} else {
				return TRUE;
			}
		} elseif ($type == 2) {
			if (!rbac::canAccess($path)) {
				jsonReturn(0, "权限不足", ["url" => $url]);
			} else {
				jsonReturn(1);
			}
		}

		return FALSE;
	}
}